package com.sky.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.sky.domain.Book;
import com.sky.exception.BookException;
import com.sky.service.BookService;
import com.sky.utils.UploadUtils;

//根据id修改图书信息
public class UpdateProductServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String,String> map = UploadUtils.HandleFormByUpload(request, getServletContext());
		
		Book book =new Book();
		try {
			BeanUtils.populate(book, map);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		//2.处理业务逻辑(修改图书信息)
		BookService bookService =new BookService();
		
		
		//设置图片的url属性
		try {
			//如果用户没有选择上传图片，则使用原来的图片
			if("".equals(book.getImgurl())||book.getImgurl()==null)
			book.setImgurl(bookService.queryBookById(book.getId()).getImgurl());
		
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			bookService.updateBookById(book);
			//修改成功
			//3.分发转向(查询图书列表的servlet： /queryBookServlet)
			request.getRequestDispatcher("queryBookServlet").forward(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//修改失败，刷新当前页，显示错误信息
			request.setAttribute("error_update_msg", e.getMessage());
			request.getRequestDispatcher("product/edit.jsp").forward(request, response);
		} catch (BookException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//修改失败，刷新当前页，显示错误信息
			request.setAttribute("error_update_msg", e.getMessage());
			request.getRequestDispatcher("product/edit.jsp").forward(request, response);
		}
		
		
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	
}
